package com.botann.projects.controller;


import com.botann.projects.base.BaseController;
import com.botann.projects.base.Model;
import com.botann.projects.base.UserDetail;
import com.botann.projects.base.UserDetailType;
import com.botann.projects.constants.API;
import com.botann.projects.constants.Code;
import com.botann.projects.constants.Constant;
import com.botann.projects.model.AdminUser;
import com.botann.projects.service.AdminUserServiceIntf;
import com.botann.projects.utils.RSAEncrypt;
import com.botann.projects.utils.SGCheckUtils;
import com.botann.projects.utils.TokenUtils;
import com.botann.projects.base.BaseController;
import com.botann.projects.base.Model;
import com.botann.projects.base.UserDetail;
import com.botann.projects.base.UserDetailType;
import com.botann.projects.constants.API;
import com.botann.projects.constants.Code;
import com.botann.projects.constants.Constant;
import com.botann.projects.model.AdminUser;
import com.botann.projects.service.AdminUserServiceIntf;
import com.botann.projects.utils.RSAEncrypt;
import com.botann.projects.utils.SGCheckUtils;
import com.botann.projects.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Charging
 * AdminUserController
 * Created by 刘山国 on 2017/11/21.
 * Copyright (c) 2017 刘山国. All rights reserved
 */
@RestController
public class AdminUserController extends BaseController {

    @Autowired
    private AdminUserServiceIntf service;

    @Override
    public Class loggerClass() {
        return AdminUserController.class;
    }

    /**
     * 未登录授权
     * @return Model
     */
    @RequestMapping(API.URL_UNAUTHORIZED)
    public Model unauthorized(){
        return failureModel(Code.SHOULD_LOGIN_ERROR,"用户未登录或登录失效!");
    }

    /**
     * 登录接口
     * @param response  HttpServletResponse
     * @param username  String
     * @param password  String
     * @param platform  String
     * @return  Model
     */
    @RequestMapping(value = API.URL_LOGIN, method = RequestMethod.POST)
    public Model login(HttpServletResponse response,
                       @RequestParam String username,
                       @RequestParam String password,
                       @RequestParam String platform) {
        try {
            AdminUser adminUser;
            if (SGCheckUtils.isLegalPhone(username)) {//判断使用手机号登录，还是用户名登录
                adminUser = service.loadAdminUserByPhone(username);
            } else {
                adminUser = service.loadAdminUserByUsername(username);
            }
            password = RSAEncrypt.decrypt(password, RSAEncrypt.RSAKeyType.PRIVATE);
            if (adminUser!=null && adminUser.getPassword().equals(password) && !adminUser.isDel()) {
                UserDetail userDetail = new UserDetail();
                userDetail.setType(UserDetailType.USER_ADMIN);
                userDetail.setId(adminUser.getId());
                TokenUtils.createToken(userDetail,platform,response);
                adminUser.setPassword(service.saveOrUpdateUserSecret(adminUser.getId(),UserDetailType.USER_ADMIN.rawValue(),password));
                return successModel(adminUser);
            } else {
                return failureModel("账号或者密码错误!");
            }
        } catch (Exception e) {
            return failureModel(e);
        }
    }

    /**
     * 退出登录
     * @param response HttpServletResponse
     * @return Model
     */
    @RequestMapping(value = API.URL_LOGOUT, method = RequestMethod.POST)
    public Model logout(HttpServletResponse response){
        TokenUtils.clearToken(response);
        return successModel("退出登录成功");
    }

    /**
     * 是否已经存在该用户名del=false
     * @param username String
     * @return Model 有true,没有false
     */
    @RequestMapping(value = API.URL_HAS_SAME_USERNAME, method = RequestMethod.POST)
    public Model hasSameUsername(@RequestParam String username){
        if (username.isEmpty()) return successModel("用户名不可空!",true);
        try {
            AdminUser adminUser = service.loadAdminUserByUsername(username);
            if (adminUser != null) {
                return successModel("用户名不可重复!",true);
            } else {
                return successModel(false);
            }
        } catch (Exception e){
            return failureModel(e);
        }
    }

    /**
     * 管理员是否已经存在该手机号 del=false
     * @param phone String
     * @return Model 有true,没有false
     */
    @RequestMapping(value = API.URL_HAS_SAME_PHONE, method = RequestMethod.POST)
    public Model hasSamePhone(@RequestParam String phone){
        if (phone.isEmpty()) return successModel(false);
        if (!SGCheckUtils.isLegalPhone(phone)) return successModel("手机号格式错误!", false);
        try {
            AdminUser adminUser = service.loadAdminUserByPhone(phone);
            if (adminUser != null) {
                return successModel("手机号不可重复!",true);
            } else {
                return successModel(false);
            }
        } catch (Exception e){
            return failureModel(e);
        }
    }

    /**
     * 添加管理员
     * @param adminUserJson String
     * @return Model
     */
    @RequestMapping(value = API.URL_ADD_ADMIN_USER, method = RequestMethod.POST)
    public Model addAdminUser(@RequestParam String adminUserJson){
        try {
            return successModel(Constant.ADD_SUCCESS,service.saveAdminUser(jsonToModel(adminUserJson,AdminUser.class)));
        } catch (Exception e){
            return failureModel(e);
        }
    }

    /**
     * 更新管理员
     * @param adminUserJson String
     * @return Model
     */
    @RequestMapping(value = API.URL_UPDATE_ADMIN_USER, method = RequestMethod.POST)
    public Model updateAdminUse(@RequestParam String adminUserJson) {
        try {
            service.updateAdminUser(adminUserJson);
            return successModel(Constant.UPDATE_SUCCESS,Constant.EMPTY);
        } catch (Exception e){
            return failureModel(e);
        }
    }


    /**
     * 重设管理员密码
     * @param userId Integer
     * @param password String
     * @return Model
     */
    @RequestMapping(value = API.URL_RESET_ADMIN_USER_PASSWORD, method = RequestMethod.POST)
    public Model resetAdminUserPassword(@RequestParam Integer userId, @RequestParam String password) {
        try {
            service.updateAdminUserPassword(userId,password);
            return successModel(Constant.UPDATE_SUCCESS,Constant.EMPTY);
        } catch (Exception e){
            return failureModel(e);
        }
    }

    /**
     * 修改密码
     * @param oldPassword 旧密码
     * @param password 新密码
     * @param confirmPassword 确认密码
     * @return model
     */
    @RequestMapping(value = API.URL_UPDATE_ADMIN_USER_PASSWORD, method = RequestMethod.POST)
    public Model updateAdminUserPassword(@RequestParam String oldPassword, @RequestParam String password, @RequestParam String confirmPassword) {
        try {
            if (!password.equals(confirmPassword)) return failureModel("两次输入的新密码不一致!");
            service.updateAdminUserPassword(oldPassword,password);
            return successModel(Constant.UPDATE_SUCCESS,Constant.EMPTY);
//            return failureModel(Code.SHOULD_LOGIN_ERROR,"密码修改成功,需要重新登录!");
        } catch (Exception e){
            return failureModel(e);
        }
    }

    /**
     * 批量删除管理员
     * @param deleteIdsJson String JSON_ARRAY
     * @return Model
     */
    @RequestMapping(value = API.URL_DELETE_ADMIN_USERS, method = RequestMethod.POST)
    public Model deleteAdminUsers(@RequestParam String deleteIdsJson){
        try {
            service.deleteAdminUsers(deleteIdsJson);
            return successModel(Constant.DELETE_SUCCESS,Constant.EMPTY);
        } catch (Exception e){
            return failureModel(e);
        }
    }

    /**
     * 各种条件查询管理员列表
     * @param username
     * @param name
     * @param roleId
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = API.URL_ADMIN_USERS, method = RequestMethod.POST)
    public Model adminUsers(String username, String name, Integer roleId, Date startDate, Date endDate){
        try {
            return successModel(service.loadAdminUsers(username,name,roleId,startDate,endDate));
        } catch (Exception e){
            return failureModel(e);
        }
    }
}
